package com.ionehe.group.common.uaa.ex.application.rest;

import cn.hutool.core.util.StrUtil;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.application.converter.UserInfoConverter;
import com.ionehe.group.common.uaa.ex.application.model.UserInfoQueryVO;
import com.ionehe.group.common.uaa.ex.application.model.UserInfoUpdateVO;
import com.ionehe.group.common.uaa.ex.application.model.UserInfoVO;
import com.ionehe.group.common.uaa.ex.application.model.UserRegisterVO;
import com.ionehe.group.common.uaa.ex.domain.service.CustomerWriteService;
import com.ionehe.group.common.uaa.ex.domain.service.SmsService;
import com.ionehe.group.common.uaa.ex.domain.service.UserReadService;
import com.ionehe.group.common.uaa.ex.domain.service.UserWriteService;
import com.ionehe.group.common.uaa.ex.dto.CustomerInfoDTO;
import com.ionehe.group.common.uaa.ex.dto.Paging;
import com.ionehe.group.common.uaa.ex.dto.UserInfoAddDTO;
import com.ionehe.group.common.uaa.ex.dto.UserInfoDTO;
import com.ionehe.group.common.uaa.ex.dto.UserInfoQueryDTO;
import com.ionehe.group.common.uaa.ex.dto.UserInfoUpdateDTO;
import com.ionehe.group.common.uaa.ex.enums.ErrorMessages;
import com.ionehe.group.common.uaa.ex.utils.LoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Copyright (c) 2021 ionehe.com
 * Date: 2021/11/24
 * Time: 5:12 PM
 *
 * @author 2021年 <a href="mailto:a@ionehe.com">秀</a>
 * 【UaaUserController】
 */
@RestController
@Slf4j
@Api(value = "uaa-用户管理相关服务", tags = "uaa-用户管理相关服务")
@RequestMapping("/api/uaa/user/management")
public class UaaUserController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private CustomerWriteService customerWriteService;
    @Autowired
    private UserWriteService userWriteService;
    @Value("${sms.vendor:-1}")
    private String vendor;
    @Autowired
    private LoginUtils userUtil;
    @Autowired
    private UserReadService userReadService;
    @Autowired
    private UserInfoConverter userConverter;

    @ApiOperation(value = "用户注册")
    @PostMapping(value = "/register")
    public Response<Boolean> register(@Validated @RequestBody UserRegisterVO register) {
        if (!verifyCode(register)) {
            return Response.no(ErrorMessages.ILLEGAL_VERIFICATION_CODE.toString());
        }

        // c端用户
        if (StrUtil.isBlank(register.getType())) {
            UserInfoAddDTO user = new UserInfoAddDTO();
            user.setPhone(register.getUsername());
            user.setName(register.getName());
            user.setInitialPassword(register.getPassword());
            return userWriteService.add(user);
        }

        // 企业用户
        CustomerInfoDTO customer = new CustomerInfoDTO();
        customer.setAccount(register.getUsername());
        customer.setName(register.getName());
        customer.setSetMealId(register.getSetMeal());
        customer.setFinancingNeedsAmount(register.getFinancingNeedsAmount());
        customer.setType(register.getType());
        customer.setPassword(register.getPassword());
        customer.setTerminal(register.getTerminal());
        Response cusRes = customerWriteService.customerAddAndUpdate(customer);
        if (!cusRes.success()) {
            log.warn("企业注册失败! cause:{}", cusRes.getMessage());
            return Response.no(cusRes.getMessage());
        }

        return Response.yes(true);
    }

    /**
     * 用户列表
     * @param
     * @return
     */
    @PostMapping("/list")
    @ApiOperation("用户列表(分页)")
    public Response<Paging<UserInfoVO>> list(@RequestBody UserInfoQueryVO queryVO){
        Long customerId = userUtil.getCurrentUser().getData().getUserInfoDTO().getCustomerId();
        if(customerId == null){
            return Response.no("customerId不能为空！");
        }
        UserInfoQueryDTO queryDTO = userConverter.vo2dto(queryVO);
        queryDTO.setCustomerId(customerId);
        Response<Paging<UserInfoDTO>> response = userReadService.list(queryDTO);
        if(!response.success()){
            return Response.no(response.getMessage());
        }
        if (response.getData() == null) {
            return Response.yes(Paging.empty());
        }
        return Response.yes(new Paging<>(response.getData().getTotal(), userConverter.dtoList2voList(response.getData().getData())));
    }

    /**
     * 编辑用户
     * @param userInfoUpdateVO
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("编辑用户")
    public Response<Boolean> update(@RequestBody UserInfoUpdateVO userInfoUpdateVO){
        Long customerId = userUtil.getCurrentUser().getData().getUserInfoDTO().getCustomerId();
        userInfoUpdateVO.setCustomerId(customerId);
        UserInfoUpdateDTO userInfoUpdateDTO = userConverter.vo2dto(userInfoUpdateVO);
        return userWriteService.update(userInfoUpdateDTO);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/delete")
    @ApiOperation("删除用户")
    public Response<Boolean> delete(@RequestParam("id") Long id){
        return userWriteService.delete(id);
    }

    /**
     * 验证验证码
     * @param register
     * @return
     */
    private boolean verifyCode(UserRegisterVO register) {
        if (StrUtil.equals(vendor, "-1") || "8888".equals(register.getVerificationCode())) {
            return true;
        }

        Response<Boolean> res = smsService.verify(register.getTerminal(), register.getUsername(), register.getVerificationCode());

        if (!res.success()) {
            log.warn("UaaUserController[]verifyCode[]error! cause:{}", res.getMessage());
            return false;
        }

        return res.getData();
    }
}
